package com.example.demo_mysql_mybatisplus.util.api.crudFree;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.web.bind.annotation.RequestBody;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/*
 * https://mp.weixin.qq.com/s/60_RFe3uFRo9SZfx580mBQ
 * */
public class FreeUtil {

    /**
     * 数据库特殊字段需要转义处理
     */
    public static String replaceSpecialCharacter(String word){
        if(null!=word){
            word = word.replaceAll("%","\\\\%").replaceAll("_","\\\\_");
        }
        return word;
    }

    /**
     * AOP中，获取请求体，并获取请求体的实例化对象
     */
    public static <T> Object getRequestBodyObjInAOP(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < joinPoint.getArgs().length; i++) {
            if (parameters[i].getAnnotation(RequestBody.class) != null){
                Object requestBodyObj = joinPoint.getArgs()[i];
                return requestBodyObj;
            }
        }
        return null;
    }


}
